package com.src;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
//Path: http://localhost/<appln-folder-name>/login
@Path("/login")
public class Login {
	
	private String error_msg;
	// HTTP Get Method
	@GET 
	// Path: http://localhost/<appln-folder-name>/login/dologin
	@Path("/dologin")
	// Produces JSON as response
	@Produces(MediaType.APPLICATION_JSON+ ";charset=utf-8") 
	// Query parameters are parameters: http://localhost/<appln-folder-name>/login/dologin?username=abc&password=xyz
	public String doLogin(@QueryParam("username") String uname, @QueryParam("password") String pwd){
		Boolean response = checkCredentials(uname, pwd);
		String result = null;
		if(response== null){
			result = Utitlity.constructJSON("false",error_msg);
		}else if(response){
			result = Utitlity.constructJSON("true","User is found");
		} else {
			result = Utitlity.constructJSON("false","Incorrect Email or Password");
		}
	return result;		
	}
	
	/**
	 * Method to check whether the entered credential is valid
	 * 
	 * @param uname
	 * @param pwd
	 * @return
	 */
	private Boolean checkCredentials(String uname, String pwd){
		Boolean result = null;
		if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){
			try {
				result = DBConnection.checkLogin(uname, pwd);
			
			} catch (Exception e) {
				error_msg="Database exception :" + e.toString();
				result = null;
			}
		}else{
			error_msg = "Username and password cannot be empty!";
			result = null;
		}
			
		return result;
	}
	
}
